import os

class Config:
    """应用基础配置类"""
    
    # 基础配置
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key-change-in-production'
    COMIC_PATH = os.environ.get('COMIC_PATH') or os.path.join(os.getcwd(), 'comics')
    CACHE_DIR = os.environ.get('CACHE_DIR') or os.path.join(os.getcwd(), 'cache')
    
    # Flask配置
    FLASK_HOST = os.environ.get('FLASK_HOST') or '0.0.0.0'
    FLASK_PORT = int(os.environ.get('FLASK_PORT') or 5000)
    DEBUG = os.environ.get('DEBUG', 'False').lower() == 'true'
    
    # 缓存配置
    CACHE_TIMEOUT = int(os.environ.get('CACHE_TIMEOUT') or 604800)  # 7天
    MAX_CACHE_SIZE = int(os.environ.get('MAX_CACHE_SIZE') or 2)  # 2GB
    
    # 图片处理配置
    SUPPORTED_FORMATS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp']
    THUMBNAIL_SIZE = (300, 400)
    IMAGE_QUALITY = 85
    
    # 分页配置
    COMICS_PER_PAGE = 20
    PAGES_PER_LOAD = 10
    
    # 预加载配置
    PRELOAD_ADJACENT_PAGES = 2  # 预加载前后2页
    PRELOAD_NEXT_CHAPTER = True  # 是否预加载下一章节的前几页
    
    @staticmethod
    def init_app(app):
        """初始化应用配置"""
        # 确保必要的目录存在
        os.makedirs(Config.COMIC_PATH, exist_ok=True)
        os.makedirs(Config.CACHE_DIR, exist_ok=True)
        os.makedirs(os.path.join(Config.CACHE_DIR, 'images'), exist_ok=True)
        os.makedirs(os.path.join(Config.CACHE_DIR, 'thumbnails'), exist_ok=True)

class DevelopmentConfig(Config):
    """开发环境配置"""
    DEBUG = True
    FLASK_ENV = 'development'

class ProductionConfig(Config):
    """生产环境配置"""
    DEBUG = False
    FLASK_ENV = 'production'
    
    @classmethod
    def init_app(cls, app):
        Config.init_app(app)
        
        # 生产环境特定配置
        import logging
        from logging.handlers import RotatingFileHandler
        
        if not app.debug:
            file_handler = RotatingFileHandler(
                'logs/comic_reader.log', 
                maxBytes=10240000, 
                backupCount=10
            )
            file_handler.setFormatter(logging.Formatter(
                '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
            ))
            file_handler.setLevel(logging.INFO)
            app.logger.addHandler(file_handler)
            app.logger.setLevel(logging.INFO)

class DockerConfig(ProductionConfig):
    """Docker环境配置"""
    COMIC_PATH = '/app/comics'
    CACHE_DIR = '/app/cache'

# 配置字典
config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'docker': DockerConfig,
    'default': DevelopmentConfig
}